import React, { Component } from 'react';
import _ from 'underscore';

import dispatcher from 'lib/dispatcher';

export default class AutoSizeLink extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {};

    this.isResize = false;
    this.reset = false;
  } // constructor

  componentDidMount() {
    if (this.refs.root.offsetHeight > 30) {
      this.isResize = true;

      this.setState({
        width: this.refs.root.offsetWidth,
        whiteSpace: 'nowrap',
        display: 'block'
      });
    }
  } // componentDidMount

  componentWillReceiveProps(nextProps) {
    if (this.isResize) {
      this.reset = true;

      this.setState({
        width: 'auto',
        whiteSpace: 'initial',
        display: 'inline'
      });
    }
  } // componentWillReceiveProps

  componentDidUpdate() {
    if (this.isResize && this.reset) {
      this.reset = false;

      this.setState({
        width: this.refs.root.offsetWidth,
        whiteSpace: 'nowrap',
        display: 'block'
      });
    }
  } // componentDidUpdate

  render() {
    let { fmtVal, rowData, styles, attrs } = this.props;

    return (
      <div ref="root">
        <a
          className="link-in-list"
          style={_.extend({
            textOverflow: 'ellipsis',
            overflow: 'hidden'
          }, this.state, styles)}
          title={ fmtVal }
          {...attrs}
          href={'#/trace/'+rowData.traceId+'/timestamp/'+rowData.timestamp}>
          { fmtVal }
        </a>
      </div>
    );
  } // render
}

AutoSizeLink.defaultProps = {
  fmtVal: null,
  rowData: null,
  styles: {},
  attrs: null
}
